package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;


    @Override
    public Result queryList() {
        ShopType shopType = new ShopType();
        //1.从redis中获取缓存
        String listJson = stringRedisTemplate.opsForValue().get("cache:shopType:" + shopType.getName());

        //2.如果缓存中有数据，则直接返回缓存数据
        if (listJson != null) {
            List<ShopType> typelist = JSONUtil.toList(listJson, ShopType.class);
            return Result.ok(typelist);

        }

        //3.如果缓存中没有数据，则从数据库中查询数据，并将数据缓存到redis中，然后返回数据
        List<ShopType> typelist = query().orderByAsc("sort").list();
        if (typelist == null || typelist.size() == 0) {
            return Result.fail("分类不存在");
        }
        stringRedisTemplate.opsForValue().set("cache:shopType:" + shopType.getName(), JSONUtil.toJsonStr(typelist));

        return Result.ok(typelist);
    }
}
